package cn.zhentao.controller;

import cn.zhentao.common.Result;
import cn.zhentao.pojo.User;
import cn.zhentao.service.UserService;

import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;

    // 阿里云短信服务配置
    private static final String HOST = "https://gyytz.market.alicloudapi.com";
    private static final String PATH = "/sms/smsSend";
    private static final String METHOD = "POST";
    private static final String APPCODE = "b01a78ea776f451091a4e9ef78ff047b";
    private static final String SMS_SIGN_ID = "2e65b1bb3d054466b82f0c9d125465e2";
    private static final String TEMPLATE_ID = "908e94ccf08b4476ba6c876d13f084ad";

    @PostMapping
    public Map<String, Object> login(@RequestBody Map<String, String> loginUser) {
        Map<String, Object> result = new HashMap<>();
        String phone = loginUser.get("phonenumber");
        String username = loginUser.get("username");
        String password = loginUser.get("password");

        if ((phone == null && username == null) || password == null) {
            result.put("code", 400);
            result.put("message", "手机号/用户名和密码不能为空");
            return result;
        }

        User user = null;
        if (phone != null) {
            user = userService.getUserByPhone(phone);
        }
        if (user == null && username != null) {
            user = userService.getUserByUsername(username);
        }
        if (user == null) {
            result.put("code", 401);
            result.put("message", "用户不存在");
            return result;
        }

        boolean passwordMatch = false;
        if (passwordEncoder != null) {
            passwordMatch = passwordEncoder.matches(password, user.getPassword());
        } else {
            passwordMatch = password.equals(user.getPassword());
        }
        if (!passwordMatch) {
            result.put("code", 401);
            result.put("message", "密码错误");
            return result;
        }

        // 生成真正的JWT token
        String jwtToken = userService.generateJwtToken(user);

        // 构建返回数据
        result.put("code", 200);
        result.put("message", "登录成功");
        Map<String, Object> data = new HashMap<>();
        data.put("token", jwtToken);
        user.setPassword(null);
        data.put("user", user);
        result.put("data", data);

        return result;
    }

    // 发送手机验证码
    @PostMapping("/code")
    public Result<String> sendCode(@RequestParam("phone") String phone, HttpSession session) {
        // 验证手机号格式
        if (phone == null || phone.trim().isEmpty()) {
            return Result.error("手机号不能为空");
        }
        if (!isValidPhoneNumber(phone)) {
            return Result.error("手机号格式不正确");
        }
        return userService.sendCode(phone, session);
    }

    // 手机验证码登录
    @PostMapping("/phone")
    public Result<java.util.Map<String, Object>> loginByCode(@RequestParam("phone") String phone, @RequestParam("code") String code, HttpSession session) {
        // 验证参数
        if (phone == null || phone.trim().isEmpty()) {
            return Result.error("手机号不能为空");
        }
        if (code == null || code.trim().isEmpty()) {
            return Result.error("验证码不能为空");
        }
        if (!isValidPhoneNumber(phone)) {
            return Result.error("手机号格式不正确");
        }
        return userService.loginByCode(phone, code, session);
    }

    // 生成6位随机验证码
    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    // 校验手机号格式
    private boolean isValidPhoneNumber(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();

        // 验证必填字段
        if (user.getUsername() == null || user.getPassword() == null || user.getPhonenumber() == null) {
            result.put("code", 400);
            result.put("message", "用户名、密码和手机号不能为空");
            return result;
        }

        // 验证手机号格式
        if (!isValidPhoneNumber(user.getPhonenumber())) {
            result.put("code", 400);
            result.put("message", "手机号格式不正确");
            return result;
        }

        // 检查用户名是否已存在
        if (userService.getUserByUsername(user.getUsername()) != null) {
            result.put("code", 409);
            result.put("message", "用户名已存在");
            return result;
        }

        // 检查手机号是否已存在
        if (userService.getUserByPhone(user.getPhonenumber()) != null) {
            result.put("code", 409);
            result.put("message", "手机号已被注册");
            return result;
        }

        // 密码加密
        if (passwordEncoder != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        // 设置默认值
        if (user.getStatus() == null) user.setStatus(0);
        if (user.getDelFlag() == null) user.setDelFlag("0");
        if (user.getNickname() == null) user.setNickname(user.getUsername()); // 默认昵称为用户名
        if (user.getUserType() == null) user.setUserType("00"); // 默认用户类型
        if (user.getSex() == null) user.setSex("2"); // 默认性别为未知

        boolean success = userService.save(user);
        if (success) {
            result.put("code", 200);
            result.put("message", "注册成功");
        } else {
            result.put("code", 500);
            result.put("message", "注册失败");
        }
        return result;
    }

    @PostMapping("/reset-test-passwords")
    public Map<String, Object> resetTestPasswords() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 重置测试用户密码为 123456
            String[] usernames = {"admin", "teacher", "student"};
            String newPassword = "123456";

            for (String username : usernames) {
                User user = userService.getUserByUsername(username);
                if (user != null) {
                    if (passwordEncoder != null) {
                        user.setPassword(passwordEncoder.encode(newPassword));
                    } else {
                        user.setPassword(newPassword);
                    }
                    userService.updateById(user);
                }
            }

            result.put("code", 200);
            result.put("message", "密码重置成功，所有测试用户密码已设置为: 123456");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "密码重置失败: " + e.getMessage());
        }

        return result;
    }
}
